import { Dropdown, Icon, Input, Menu, Modal, Tree ,Form} from "antd"
import styles from './index.less'
import React from "react";
import { docCategoryListById } from "@/services/knowledgeFile";

const TreeShape = (props) => {
  //节点操作需要用到的变量
  //optNode => 当前点击操作按钮的节点数据
  //currentNode => 当前选中按钮的节点数据

  //deleteDisabled => 是否有删除权限
  //moveDisabled => 是否有移动权限
  //addDisabled => 是否有新增权限
  //editDisabled => 是否有编辑权限

  const { optNode,currentNode,deleteDisabled,moveDisabled,addDisabled,editDisabled,form:{getFieldDecorator,setFieldsValue,validateFields,resetFields} } = props;
  const [visible,setVisible] = React.useState(false)
  const [editOrAdd,setEditOrAdd] = React.useState('')


  const foldSvg = () => (
    <svg width="16" height="17" viewBox="0 0 16 17" fill="none" >
        <g clip-path="url(#clip0_1_4851)">
          <g filter="url(#filter0_f_1_4851)">
            <path d="M2.11464 8.05859L2.07038 12.6176C2.06332 13.3441 2.62788 13.937 3.3271 13.9376L12.6909 13.9453C13.3916 13.9459 13.9577 13.3514 13.9496 12.6234L13.8986 8.05859H2.11464Z" fill="#2C6BF5" />
          </g>
          <path d="M0.751936 3.45999C0.758357 2.58963 1.46084 1.88485 2.33117 1.87557L6.86695 1.82724C7.41052 1.82144 7.9156 2.10708 8.19078 2.57589L8.55567 3.27194C8.56851 3.29643 8.5939 3.31176 8.62155 3.31172L13.6792 3.30375C14.5543 3.30237 15.2674 4.00578 15.2779 4.88079L15.2959 6.37093L15.1431 6.33254C15.0735 6.31505 15.0022 6.30569 14.9304 6.30464L13.7824 6.28795L1.00979 6.29716L0.900585 6.31894C0.860805 6.32687 0.821656 6.33768 0.783448 6.3513L0.730469 6.37019L0.751936 3.45999Z" fill="#FBB956" />
          <path d="M2.24219 5.43529C2.24219 5.08675 2.52474 4.8042 2.87328 4.8042H13.1793C13.5279 4.8042 13.8104 5.08675 13.8104 5.43529V6.2829H2.24219V5.43529Z" fill="#FFFDF8" />
          <g filter="url(#filter1_f_1_4851)">
            <rect x="2.24219" y="6.54468" width="11.5682" height="7.30457" rx="0.63109" fill="#F3F7FF" />
          </g>
          <g filter="url(#filter2_b_1_4851)">
            <path d="M0.10775 7.37578C0.0581804 6.79092 0.51953 6.28882 1.10649 6.28882H14.9346C15.5136 6.28882 15.9722 6.77803 15.9348 7.35585L15.4554 14.7659C15.4023 15.5862 14.7215 16.2243 13.8995 16.2243H2.29031C1.48025 16.2243 0.805128 15.604 0.736717 14.7969L0.10775 7.37578Z" fill="#F5C741" fill-opacity="0.9" />
          </g>
        </g>
        <defs>
          <filter id="filter0_f_1_4851" x="-0.157066" y="5.83122" width="16.3342" height="10.3415" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
            <feFlood flood-opacity="0" result="BackgroundImageFix" />
            <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
            <feGaussianBlur stdDeviation="1.11369" result="effect1_foregroundBlur_1_4851" />
          </filter>
          <filter id="filter1_f_1_4851" x="0.386039" y="4.68853" width="15.2807" height="11.017" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
            <feFlood flood-opacity="0" result="BackgroundImageFix" />
            <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
            <feGaussianBlur stdDeviation="0.928074" result="effect1_foregroundBlur_1_4851" />
          </filter>
          <filter id="filter2_b_1_4851" x="0.029758" y="6.21457" width="15.9815" height="10.084" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
            <feFlood flood-opacity="0" result="BackgroundImageFix" />
            <feGaussianBlur in="BackgroundImageFix" stdDeviation="0.037123" />
            <feComposite in2="SourceAlpha" operator="in" result="effect1_backgroundBlur_1_4851" />
            <feBlend mode="normal" in="SourceGraphic" in2="effect1_backgroundBlur_1_4851" result="shape" />
          </filter>
          <clipPath id="clip0_1_4851">
            <rect width="16" height="16" fill="white" transform="translate(0 0.970215)" />
          </clipPath>
        </defs>
      </svg>
  )

  //选中节点
  const onSelect = (selectedKeys,e) => {
    if(props.nodeSelect){
      props.nodeSelect(selectedKeys,e)
    }
  }

  //节点展开收起
  const onExpand = (expandedKeys,{node}) => {
    if(props.nodeExpand){
      props.nodeExpand(expandedKeys,node)
    }
  }

  //节点移动
  const doNodeMove = (e,flag,item) => {
    e.persist()
    e.stopPropagation();
    if(props.nodeMove){
      props.nodeMove(flag,item)
    }
  }

  //树节点更多操作
  const menu = (
    <Menu>
      {
        editDisabled ? '' :(
          <Menu.Item key="1" onClick={(e) => setNodeModalStatus(e,true)} disabled={editDisabled}>
            <Icon type="form" style={{fontSize:14}} />
            <span>编辑名称</span>
          </Menu.Item>
        )
      }
      {
        deleteDisabled ? '' : (
          <Menu.Item key="5" onClick={e => deleteConfirm(e)} disabled={deleteDisabled}>
            <Icon type="delete" style={{fontSize:14}} />
            <span>删除</span>
          </Menu.Item>
        )
      }
      {
        props.nodeMove && !moveDisabled ? (
          <Menu.Item key="2" onClick={e => doNodeMove(e,0)} disabled={moveDisabled}>
            <Icon type="arrow-up" style={{fontSize:14}} />
            <span>上移</span>
          </Menu.Item>
        ) : ''
      }
      {
        props.nodeMove && !moveDisabled ? (
          <Menu.Item key="3" onClick={e => doNodeMove(e,1)} disabled={moveDisabled}>
            <Icon type="arrow-down" style={{fontSize:14}} />
            <span>下移</span>
          </Menu.Item>
        ) : ''
      }
    </Menu>
  );

  //渲染树节点名
  const renderTreeTitle = item =>  (
    <span className={styles.treeTitle}>
      <span>{item.name}</span>
      <span className='actionPart'>
        {
          addDisabled ? '' : (
            <Icon type="plus" onClick={e => openModal(e,item,'add')} />
          )
        }
        {
          item.parentId != 0 && item.parentId != 'ROOT' && !(editDisabled) ? (
            <Icon type="edit" style={{margin:"0 5px"}}  onClick={e => openModal(e,item,'edit')} />
          ) : ''
        }
        {
          item.parentId != 0 && item.parentId != 'ROOT' && !(deleteDisabled) ? (
            <Icon type="delete" onClick={e => deleteConfirm(e,item)} />
          ) : ''
        }
        {
          item.parentId != 0 && item.parentId != 'ROOT' && !(moveDisabled) && props.nodeMove ? (
            <Icon type="arrow-up" style={{margin:"0 5px"}} onClick={e => doNodeMove(e,0,item)} />
          ) : ''
        }
        {
          item.parentId != 0 && item.parentId != 'ROOT' && !(moveDisabled) && props.nodeMove ? (
            <Icon type="arrow-down" onClick={e => doNodeMove(e,1,item)} />
          ) : ''
        }
        
      </span>
    </span>
  )

  //渲染树节点
  const renderTreeNode = data => data.map(item => 
    item.children && item.children.length > 0 ? (
      <Tree.TreeNode 
        title={renderTreeTitle(item)} 
        key={item.id}
        info={{
          id:item.id,
          name:item.name,
          path: item.path,
          parentId: item.parentId,
          disabled: item.disabled,
          weight: item.weight,
        }}
        icon={<Icon component={foldSvg} />}
        dataRef={item}
        isLeaf={!item.hasChild}
        {...item}
      >
        {renderTreeNode(item.children)}
      </Tree.TreeNode>
    ) : (
      <Tree.TreeNode 
        title={renderTreeTitle(item)} 
        key={item.id} 
        info={{
          id:item.id,
          name:item.name,
          path: item.path,
          parentId: item.parentId,
          disabled: item.disabled,
          weight: item.weight,
        }}
        icon={<Icon component={foldSvg} />}
        {...item} dataRef={item}
        isLeaf={!item.hasChild}
      />
      
    )
  )

  //设置节点名称编辑状态
  // const setNodeModalStatus = (e,flag) => {
  //   if(e){
  //     e.domEvent.persist()
  //     e.domEvent.stopPropagation();
  //   }
    
  //   if(props.setOptNode){
  //     let opt = optNode
  //     opt.isEditName = flag
  //     opt.editName = optNode.name
  //     props.setOptNode(opt)
  //   }
  // }

  //编辑节点名称
  // const changeName = e => {
  //   e.persist()
  //   if(props.setOptNode){
  //     let opt = optNode
  //     opt.editName = e.target.value
  //     props.setOptNode(opt)
  //   }
  // }

  // //完成编辑节点名称时间
  // const editName = () => {
  //   const name = optNode.editName
  //   if(name == '' || name === optNode.name){
  //     setNodeModalStatus(null,false)
  //   }else{
  //     if(props.nodeUpdateName){
  //       props.nodeUpdateName(name)
  //     }
  //   }
  // }
  
  //删除节点的询问话术
  const deleteConfirm = (e,item) => {
    e.persist()
    e.stopPropagation();
    if(props.setOptNode){
      props.setOptNode(item)
    }
    Modal.confirm({
      title:"是否确定要删除？",
      okText:"确定",
      cancelText:"取消",
      okType:"danger",
      onOk:() => {
        if(props.nodeDelete){
          props.nodeDelete()
        }
      }
    })
  }

  //新增节点
  // const addName = (e,item) => {
  //   e.persist()
  //   e.stopPropagation();
  //   if(props.addNode){
  //     props.addNode(item,'未命名分类_'+generateRandom())
  //   }
  // }

  //展示当前节点的更多操作菜单
//   const showMenu = (e,item) => {
//     e.persist()
//     e.stopPropagation();
//     if(props.setOptNode){
//       console.log(item);
//       props.setOptNode(item)
//     }
//   }

//   //更多菜单显隐
//   const onVisibleChange = (visible) => {
//     if(!visible){
//       if(props.setOptNode){
//         props.setOptNode({})
//       }
//     }
//   }

//   //获取随机数
//  const generateRandom = () => {
//     return Math.floor(Math.random() * 9000) + 1000;
//   }

  const cancelModal = () => {
    resetFields()
    setVisible(false)
    props.setOptNode({})
  }

  const openModal = (e,item,flag) => {
    e.persist()
    e.stopPropagation();
    if(props.setOptNode){
      props.setOptNode(item)
    }
    setVisible(true)
    setEditOrAdd(flag)
  }

  const okValidate = () => {
    validateFields((error,values) => {
      if(!error){
        if(editOrAdd == 'add' && props.addNode){
          props.addNode(optNode,values.name)
          cancelModal()
        }else if(editOrAdd == 'edit' && props.nodeUpdateName){
          props.nodeUpdateName(values.name)
          cancelModal()
        }
      }
    })
  }

  const onLoadData = treeNode =>
    new Promise(async resolve => {
      if (treeNode.props.children || !treeNode.props.hasChild) {
        resolve();
        return;
      }
      if(props.getCategoryChildren){
        props.getCategoryChildren(treeNode,resolve)
      }else{
        resolve()
        return
      }
    });

  return (
    <div className={props.nodeMove ? `${styles.treeShape1} ${styles.treeShape2}` : `${styles.treeShape1}`}>
      <Tree
        onSelect={onSelect}
        selectedKeys={[currentNode.id]}
        expandedKeys={props.expandedKeys}
        onExpand={onExpand}
        showIcon={true}
        loadData={onLoadData}
      >
        {renderTreeNode(props.treeData)}
      </Tree>

      <Modal
        title={editOrAdd == 'edit' ? '编辑分类' : '新建分类'}
        visible={visible}
        onCancel={cancelModal}
        onOk={okValidate}
      >
        <Form>
          <Form.Item label=''>
            {
              getFieldDecorator("name",{rules:[{required:true,message:"请输入"}]})(
                <Input placeholder="分类名称" onPressEnter={okValidate} />
              )
            }
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Form.create()(TreeShape)